package timer3;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

class MyTask implements Comparable<MyTask>{
    private Runnable task;
    private long time;
    public MyTask (Runnable task, long time) {
        this.task = task;
        this.time = time + System.currentTimeMillis();
    }
    public Runnable getTask() {
        return this.task;
    }
    public long getTime() {
        return this.time;
    }
    public int compareTo(MyTask myTask) {
        return (int)(this.time - myTask.getTime());
    }
}
class MyTimer {
    private BlockingQueue<MyTask> blockingQueue = new PriorityBlockingQueue<>();
    Object locker = new Object();
    public MyTimer() {
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    synchronized (locker){
                        try {
                            //当前时间
                            long nowTime = System.currentTimeMillis();
                            //最先任务
                            MyTask nowTask = blockingQueue.take();
                            //工作时间
                            long workTime = nowTask.getTime();
                            if(workTime > nowTime){
                                //阻塞等待
                                blockingQueue.put(nowTask);
                                locker.wait(nowTask.getTime() - System.currentTimeMillis());
                            }else{
                                nowTask.getTask().run();
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        t.start();
    }
    public void schedule(Runnable task, long workTime) throws InterruptedException {
        blockingQueue.put(new MyTask(task, workTime));
        synchronized(locker) {
            locker.notify();
        }
    }

}

public class Test {
    public static void main(String[] args) throws InterruptedException {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("这是一个在3s后完成的任务");
            }
        }, 3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("这是一个在5s后完成的任务");
            }
        }, 5000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("这是一个在7s后完成的任务");
            }
        }, 7000);
    }
}
